import { useEffect, useState } from 'react';
import { Button, Divider, Space } from 'antd';
import { atom, useAtom, Provider, createStore } from 'jotai';

const fooInit = atom(1000);
fooInit.onMount = (set) => {
	console.log('=====');
	return () => {
		set(999);
		console.log('卸载了');
	};
};

const priceAtom = atom(90);
const bar = atom(10, (get, set, update) => {
	console.log('set====-', update);
	set(priceAtom, 100);
});
const myStore = createStore();

const testInit = atom(async (get, data) => {
	console.log('data:', data);
	return get(priceAtom) + 10;
});

const Child = () => {
	const [foo, setFoo] = useAtom(fooInit);
	const [test] = useAtom(testInit);
	return (
		<Space>
			<Button onClick={() => myStore.set(bar, myStore.get(bar) + 1)}>
				Child{myStore.get(bar)}
			</Button>
			<Button>fooInit {foo}</Button>
			<Button>test {test}</Button>
		</Space>
	);
};

const Son = () => {
	const [foo, setBar] = useAtom(priceAtom);
	return (
		<Space>
			<Button onClick={() => setBar(foo + 1)}>Son{foo}</Button>
			<Button
				onClick={() => {
					console.log(myStore.get(bar));
				}}
			>
				get
			</Button>
		</Space>
	);
};

const Base = () => {
	useEffect(() => () => {}, []);

	return (
		<Provider store={myStore}>
			<Child />
			<Divider type="vertical" />
			<Son />
		</Provider>
	);
};

export default Base;
